<?php
include_once 'header.php';

$op = isset($_REQUEST['op']) ? $_REQUEST['op'] : 'start';
$pid = isset($_REQUEST['pid']) ? intval($_REQUEST['pid']) : 0;

// page tpl, must after $op
$page_tpl = rb_get_pagetpl();

// handler
$project_handler =& xoops_getmodulehandler('project');
//$table_handler =& xoops_getmodulehandler('table');

// project is exists?
if (!$project_handler->isExists($pid)) {
	redirect_header('index.php', 2, 'Project not found!');
	exit();
} else {
	$thisProject = $project_handler->get($pid);
	$mod_dir = $thisProject->getVar('dirname');
}

switch($op)
{	
	case 'start':
		include_once XOOPS_ROOT_PATH.'/header.php';
		rb_add_stylesheet(XOOPS_URL.'/Frameworks/rb/style.css');
		rb_add_stylesheet(RBTOOL_URL.'/css/style.css');
		rb_add_stylesheet('', '', 'label {float:left; width:250px; padding:0 0 5px; 0}');
		$xoopsTpl->assign('xoops_pagetitle', 'Creat module prototype');
		$xoopsTpl->assign('project', $thisProject);
		
		// DB tables
		$sql = 'SELECT `TABLE_NAME` FROM information_schema.tables WHERE `TABLE_SCHEMA` LIKE '.$xoopsDB->quoteString(XOOPS_DB_NAME);
		$sql .= ' AND `TABLE_NAME` LIKE '.$xoopsDB->quoteString($thisProject->getVar('dirname').'_%');
		//echo $sql;
		$result = $xoopsDB->queryF($sql);
		//$result = $xoopsDB->queryF('SHOW TABLES FROM '.XOOPS_DB_NAME);
		while ($row = $xoopsDB->fetchRow($result)) {
			$table_list[$row[0]] = ' '.$row[0];
		}
		$xoopsTpl->assign('table_list', $table_list);
		$xoopsTpl->display(RBTOOL_TPL_PATH.'/'.$page_tpl);
		include_once XOOPS_ROOT_PATH.'/footer.php';
		break;
		
	case 'class':		
		/*
			No selected table
		*/
		if (!is_array($_POST['tables']) || !count($_POST['tables'])) {
			header('location: generate.php?op=step1&pid='.$pid);
			exit();
		}
		include_once XOOPS_ROOT_PATH.'/header.php';
		rb_add_stylesheet(XOOPS_URL.'/Frameworks/rb/style.css');
		rb_add_stylesheet(RBTOOL_URL.'/css/style.css');
		$xoopsTpl->assign('xoops_pagetitle', 'Setting Object Handler');
		$xoopsTpl->assign('project', $thisProject);
		
		foreach ($_POST['tables'] as $sel_table) {
			$sel_table = str_replace(XOOPS_DB_PREFIX.'_', '', $sel_table);
			$tables = array();
			$tables['name'] = $sel_table;
			$tables['fields'] = array();
			$result = $xoopsDB->queryF('SHOW FIELDS FROM '.$sel_table);
			while ($row = $xoopsDB->fetchArray($result)) {
				$tables['fields'][] = array(
					'name' => $row['Field'],
					'extra' => $row['Extra']
				);
				/*$fields['type']    = $row['Type'];
				$fields['null']    = $row['Null'];
				$fields['key']     = $row['Key'];
				$fields['default'] = $row['Default'];
				$fields['extra']   = $row['Extra'];*/
			}
			//print_r($tables);
			$xoopsTpl->append('tables', $tables);
		}
		$xoopsTpl->display(RBTOOL_TPL_PATH.'/'.$page_tpl);
		include_once XOOPS_ROOT_PATH.'/footer.php';
		break;
		
	case 'step1':
	
		/*
			cache selected tables
		*/
		$_SESSION['mytables'] = array();
		foreach ($_POST['tables'] as $key => $table) {
			$_SESSION['mytables'][$key]['name'] = $table['name'];
			$_SESSION['mytables'][$key]['primary'] = $table['primary'];
			$_SESSION['mytables'][$key]['order_by'] = $table['order_by'];
			$_SESSION['mytables'][$key]['order_type'] = $table['order_type'];
		}
		/*
			create include  directory
		*/
		rbtool_mkdir(RBTOOL_COPY_PATH.'/'.$mod_dir, false);
		rbtool_mkdir(RBTOOL_COPY_PATH.'/'.$mod_dir.'/include');
		rbtool_mkdir(RBTOOL_COPY_PATH.'/'.$mod_dir.'/images');
		rbtool_mkdir(RBTOOL_COPY_PATH.'/'.$mod_dir.'/templates');
		rbtool_mkdir(RBTOOL_COPY_PATH.'/'.$mod_dir.'/admin', false);
		rbtool_mkdir(RBTOOL_COPY_PATH.'/'.$mod_dir.'/blocks');
		/*
			copy slogo.png
		*/
		$sample_slogo = RBTOOL_IMG_PATH.'/xoops_slogo.png';
		$copy_slogo = RBTOOL_COPY_PATH.'/'.$mod_dir.'/images/'.$mod_dir.'_slogo.png';
		@copy($sample_slogo, $copy_slogo);
		/*
			copy header.php
		*/
		$sample_header = RBTOOL_SAMPLE_PATH.'/header.txt';
		$copy_header = RBTOOL_COPY_PATH.'/'.$mod_dir.'/header.php';
		@copy($sample_header, $copy_header);
		/*
			copy index.php
		*/
		$sample_index = RBTOOL_SAMPLE_PATH.'/index.txt';
		$copy_index = RBTOOL_COPY_PATH.'/'.$mod_dir.'/index.php';
		@copy($sample_index, $copy_index);
		/*
			copy tpl.html
		*/
		$sample_tpl = RBTOOL_SAMPLE_PATH.'/tpl.txt';
		$copy_tpl = RBTOOL_COPY_PATH.'/'.$mod_dir.'/templates/'.$mod_dir.'_index_list.html';
		@copy($sample_tpl, $copy_tpl);
		/*
			create xoops_version.php
		*/
		$search = array();
		$replace = array();
		$search[] = '{MOD_NAME_UP}';
		$replace[] = strtoupper($mod_dir);
		$search[] = '{MOD_NAME_LOW}';
		$replace[] = strtolower($mod_dir);
		
		$search[] = '{PROJECT_NAME}';
		$replace[] = $thisProject->getVar('name');
		$search[] = '{PROJECT_VER}';
		$replace[] = $thisProject->getVar('version');
		$search[] = '{PROJECT_DESC}';
		$replace[] = $thisProject->getVar('description');
		$search[] = '{PROJECT_CREDITS}';
		$replace[] = $thisProject->getVar('credits');
		$search[] = '{PROJECT_AUTHOR}';
		$replace[] = $thisProject->getVar('author');
		$search[] = '{PROJECT_LICENSE}';
		$replace[] = $thisProject->getVar('license');
		//  convert sql string
		if (is_array($_SESSION['mytables']) && count($_SESSION['mytables'])) {
			$sql_str = "// Sql file\n";
			$sql_str .= "\$modversion['sqlfile']['mysql'] = 'sql/mysql.sql';\n";
			$sql_str .= "// Tables created by sql file (without prefix!)\n";
			foreach ($_SESSION['mytables'] as $key => $val) {
				if ($key > 0) {
					$sql_str .= "\$t++;\n";
				} else {
					$sql_str .= "\$t=1;\n";
				}
				$tb = str_replace($mod_dir, '', $val['name']);
				$sql_str .= "\$modversion['tables'][\$t] = \$mydirname.'{$tb}';\n";
			}
			$sql_str .= "\n";
			$search[] = '{PROJECT_SQLSTR}';
			$replace[] = $sql_str;
		}
		// Admin backend
		$search[] = '{PROJECT_HASADMIN}';
		if ($thisProject->getVar('hasadmin')) {
			$admin_str = "\$modversion['hasAdmin'] = 1;\n";
			$admin_str .= "\$modversion['adminindex'] = '{$thisProject->getVar('adminindex')}';\n";
			$admin_str .= "\$modversion['adminmenu'] = '{$thisProject->getVar('adminmenu')}';\n";
			$replace[] = $admin_str;
		} else {
			$replace[] = "\$modversion['hasAdmin'] = 0;\n";
		}
		// Menu & Sub Menu
		$search[] = '{PROJECT_HASMAIN}';
		if ($thisProject->getVar('hasmain')) {
			$replace[] = "\$modversion['hasMain'] = 1;\n";
		} else {
			$replace[] = "\$modversion['hasMain'] = 0;\n";
		}
		$sample_version = RBTOOL_SAMPLE_PATH.'/xoops_version.txt';
		@chmod($sample_version, 0777);
		if ($fh = fopen($sample_version, 'r+')) {
			$contents = fread($fh, filesize($sample_version));
			$new_contents = str_replace($search, $replace, $contents);
			//rbtool_mkdir(RBTOOL_COPY_PATH.'/'.$mod_dir.'/class');
			$copy_version = RBTOOL_COPY_PATH.'/'.$mod_dir.'/xoops_version.php';
			if ($fh2 = fopen($copy_version, 'w')) {
				fwrite($fh2, $new_contents, strlen($new_contents) );
				fclose($fh2);
			}
			fclose($fh);
		}
		header('location: generate.php?op=step2&pid='.$pid);
		break;
		
	case 'step2':
		/*
			create functions.php
		*/
		$search[] = '{MOD_NAME_UP}';
		$replace[] = strtoupper($mod_dir);
		$search[] = '{MOD_NAME_LOW}';
		$replace[] = strtolower($mod_dir);
		
		$file = RBTOOL_PATH.'/sample/functions.txt';
		@chmod($file, 0777);
		
		if ($fh = fopen($file, 'r+')) {
			$contents = fread($fh, filesize($file));
			$new_contents = str_replace($search, $replace, $contents);
			$copy = RBTOOL_COPY_PATH.'/'.$mod_dir.'/include/functions.php';
			if ($fh2 = fopen($copy, 'w')) {
				fwrite($fh2, $new_contents, strlen($new_contents) );
				fclose($fh2);
			}
			fclose($fh);
		}
		header('location: generate.php?op=step3&pid='.$pid);
		break;
		
	case 'step3':
		/*
			create class  directory
		*/
		rbtool_mkdir(RBTOOL_COPY_PATH.'/'.$mod_dir.'/class');
		/*
			for every table create object handler file
		*/
		foreach ($_SESSION['mytables'] as $table) {
			//echo $table['name'].'<br />';
			$constructor = '';
			$result = $xoopsDB->queryF('SHOW FIELDS FROM '.$xoopsDB->prefix($table['name']));
			while ($row = $xoopsDB->fetchArray($result)) {
				$constructor .= "\n";
				$constructor .= '		$this->initVar(';
				$constructor .= $xoopsDB->quoteString($row['Field']);
				$constructor .= ', '.rbtool_get_datatype($row['Type']);
				$constructor .= ', '.rbtool_get_default_value($row['Default']);
				$constructor .= ', false';
				if (rbtool_get_datatype($row['Type']) == 'XOBJ_DTYPE_TXTBOX') {
					$constructor .= ', '.rbtool_get_maxlength($row['Type']);
				}
				$constructor .= ');';
			}
			$mod_table = $table['name'];
			$search = array();
			$replace = array();
			
			$search[] = '{CLASS_CONSTRUCTOR}';
			$replace[] = $constructor;
			$search[] = '{CLASS_PRIMARY}';
			$replace[] = $table['primary'];
			$search[] = '{CLASS_ORDER}';
			$replace[] = $table['order_by'].' '.$table['order_type'];
			$search[] = '{MOD_NAME_UP}';
			$replace[] = strtoupper($mod_dir);
			$search[] = '{MOD_NAME_LOW}';
			$replace[] = strtolower($mod_dir);
			$search[] = '{MOD_NAME_UCF}';
			$replace[] = ucfirst($mod_dir);
			$search[] = '{TABLE_NAME_LOW}';
			$replace[] = strtolower($mod_table);
			$search[] = '{CLASS_NAME_CAMEL}';
			$replace[] = rbtool_get_camel_case($mod_table);
			
			$file = RBTOOL_PATH.'/sample/class.txt';
			@chmod($file, 0777);
			
			if ($fh = fopen($file, 'r+')) {
				$contents = fread($fh, filesize($file));
				$new_contents = str_replace($search, $replace, $contents);
				$handler = str_replace($mod_dir.'_', '', strtolower($mod_table));
				$copy = RBTOOL_COPY_PATH.'/'.$mod_dir.'/class/'.$handler.'.php';
				if ($fh2 = fopen($copy, 'w')) {
					fwrite($fh2, $new_contents, strlen($new_contents) );
					fclose($fh2);
				}
				fclose($fh);
			}
		}
		header('location: generate.php?op=step4&pid='.$pid);
		break;
		
	case 'step4':
		/*
			dump sql
		*/
		if (is_array($_SESSION['mytables']) && count($_SESSION['mytables'])) {
			rbtool_mkdir(RBTOOL_COPY_PATH.'/'.$mod_dir.'/sql');
			$str = '';
			foreach ($_SESSION['mytables'] as $table) {
				
				$sql = 'SHOW CREATE TABLE '.$table['name'];
				//$xoopsDB->queryF('SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";');
				$result = $xoopsDB->queryF($sql);
				list($table, $CreateTable)  = $xoopsDB->fetchRow($result);
				$CreateTable = preg_replace('/ENGINE=MyISAM/', 'TYPE=MyISAM', $CreateTable);
				$CreateTable = preg_replace('/AUTO_INCREMENT\s*=\s*([0-9])+/', '', $CreateTable);
				$CreateTable = preg_replace('/DEFAULT CHARSET\s*=\s*([a-zA-Z0-9])+/', '', $CreateTable);
				$str .= $CreateTable.";\n\n";
			}
			//echo '<pre>'.$str.'</pre>';
			$copy = RBTOOL_COPY_PATH.'/'.$mod_dir.'/sql/mysql.sql';
			if ($fh = fopen($copy, 'w')) {
				fwrite($fh, $str, strlen($str) );
				fclose($fh);
			}
		}
		header('location: generate.php?op=finish&pid='.$pid);
		break;
		
	case 'finish':
		unset($_SESSION['mytables']);
		include_once XOOPS_ROOT_PATH.'/header.php';
		rb_add_stylesheet(XOOPS_URL.'/Frameworks/rb/style.css');
		$xoopsTpl->assign('xoops_pagetitle', 'Creat module prototype');
		$xoopsTpl->assign('project', $thisProject);
		$xoopsTpl->assign('copy_path', RBTOOL_COPY_PATH);
		$xoopsTpl->display(RBTOOL_TPL_PATH.'/'.$page_tpl);
		include_once XOOPS_ROOT_PATH.'/footer.php';
		break;
	
}

?>